<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\base\BaseController;
use app\home\validate\EnterpriseCheck;
use app\home\validate\GoodsCheck;
use app\home\validate\ItemCheck;
use Overtrue\Pinyin\Pinyin;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Goods extends BaseController
{
    /**
     * 商品管理
     */
    public function index()
    {
        if (request()->isAjax()) {
            $param = get_params();
            $where = array();

            $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

            if($eid > 0){
                $where[] = ['eid' , '=' , $eid];
            }

            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }

            $where[] = ['status', '>=', 0];
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $content = Db::name('Goods')
                ->order('eid asc,create_time desc')
                ->where($where)
                ->paginate($rows, false, ['query' => $param])->toArray();

            foreach($content['data'] as $key => &$value){

                $value['fmt_out_time'] = !empty($vaue['out_time']) && $value['out_time'] > 0 ? date('Y-m-d' , $value['out_time']) : '' ;

                //查询项目
                $item =  Db::name('Item')->where(['id'=>$value['item_id']])->find();
                $value['item_name'] = $item['name'] ?? '';
                $deparment = Db::name('Enterprise')->where(['id'=>$value['eid']])->find();
                $value['d_name'] = $deparment['title'] ?? '系统管理员';


                $value['all_price'] = round($value['num'] * $value['price'] , 2);
            }
            return table_assign(0, '', $content);
        } else {

            return view();
        }
    }

    /**
     * 添加/编辑商品商品
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            if (!empty($param['id']) && $param['id'] > 0) {
                try {
                    validate(GoodsCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['update_time'] = time();
                $res = Db::name('Goods')->strict(false)->field(true)->update($param);
                if ($res) {
                    add_log('edit', $param['id'], $param);
                }
                return to_assign();
            } else {
                try {
                    validate(GoodsCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(1, $e->getError());
                }
                $param['uid']   = $this->uid;
                $param['create_time'] = time();
                $insertId = Db::name('Goods')->strict(false)->field(true)->insertGetId($param);
                if ($insertId) {
                    add_log('add', $insertId, $param);
                }
                return to_assign();
            }
        }else {
            if($this->eid > 0){
                //查询企业
                $enterprise = Db::name('Enterprise')->where('id',$this->eid)->where('status', '>=', 0)->order('create_time asc')->select();
            }else{
                //查询企业
                $enterprise = Db::name('Enterprise')->where('status', '>=', 0)->order('create_time asc')->select();
            }

            View::assign('enterprise', $enterprise);
            View::assign('eid', $this->eid);

            $detail = [];
            if (!empty($param['id']) && $param['id'] > 0) {
                //查询商品
                $detail = Db::name('goods')->where(['id' => $param['id']])->find();

                $detail['fmt_end_time'] = !empty($detail['end_time']) && $detail['end_time'] > 0 ? date('Y-m-d' , $detail['end_time']) : '' ;
            }
            View::assign('detail', $detail);
            return view();

        }
    }

    //批量导入物料
    public function fileGoods(){

        $eid = $this->eid;
        ini_set('memory_limit','512M');
        // 获取表单上传文件
        $file[]= request()->file('file');

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])->check($file);
            // 日期前綴
            $dataPath = date('Ym');
            $md5 = $file[0]->hash('md5');
            $savename = \think\facade\Filesystem::disk('public')->putFile($dataPath, $file[0], function () use ($md5) {
                return $md5;
            });
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $path = get_config('filesystem.disks.public.url');
            // 读取文件，tp6默认上传的文件，在runtime的相应目录下，可根据实际情况自己更改
            $objPHPExcel = $objReader->load('.'.$path . '/' .$savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;

            if ($lines <= 0) {
                return to_assign(1, '数据不能为空');
                exit();
            }

            Db::startTrans();

            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            $pinyin = new Pinyin();
            for ($j = 4; $j <= $highestRow; $j++) {

                $name   = $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue();//物料名称
                $warehouse  = $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue();//仓库
                $code  = $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue();//物料编码
                $version  = $objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue();//规格型号
                $unit  = $objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue();//单位
                $num  = $objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue();//库存数量
                $price  = $objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue();//单价

                $info = [
                    'eid'                   => $eid,
                    'name'                  => $name,
                    'warehouse'             => $warehouse,
                    'code'                  => $code,
                    'version'               => $version,
                    'unit'                  => $unit,
                    'num'                   => $num,
                    'price'                 => $price,
                    'create_time'           => time(),
                ];
                if(empty($name)){
                    return to_assign(1, '第'.($j - 1).'行的物料名称为必填项');
                }
                if(empty($warehouse)){
                    return to_assign(1, '第'.($j - 1).'行的仓库为必填项');
                }
                if(empty($code)){
                    return to_assign(1, '第'.($j - 1).'行的物料编码为必填项');
                }
                if(empty($version)){
                    return to_assign(1, '第'.($j - 1).'行的规格型号为必填项');
                }
                if(empty($unit)){
                    return to_assign(1, '第'.($j - 1).'行的单位为必填项');
                }
                if(empty($price)){
                    return to_assign(1, '第'.($j - 1).'行的物为必填项');
                }
                if(empty($num)){
                    return to_assign(1, '第'.($j - 1).'行的数量为必填项');
                }

                $arr[] = $info;
            }

            // 批量添加数据
            if (DB::name('Goods')->insertAll($arr)) {
                Db::commit();
                return to_assign(0, '导入成功');
            }
            else{
                Db::rollbak();
                return to_assign(1, '导入失败，请检查excel文件再试');
            }

        } catch (\think\exception\ValidateException $e) {
            return to_assign(1, $e->getMessage());
        }
    }

    /**
     * 操作商品
     * @return \json
     */
    public function opertion()
    {
        $param = get_params();
        $res = Db::name('Item')->strict(false)->field('id,status')->update($param);
        if ($res) {
            if($param['status'] == 1){
                add_log('disable', $param['id'], $param);
            }
            else if($param['status'] == 2){
                add_log('open', $param['id'], $param);
            }
            return to_assign();
        }
        else{
            return to_assign(0, '操作失败');
        }
    }

    //删除
    public function delete()
    {
        $id = get_params("id");
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        $data['delete_time'] = time();
        if (Db::name('Goods')->update($data) !== false) {
            add_log('delete', $id, $data);
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "删除失败");
        }
    }

    //删除
    public function delete_all()
    {
        $param = get_params();
        $eid = !empty($param['eid']) ? $param['eid']: $this->eid;

        $data['status'] = '-1';
        $data['update_time'] = time();
        $data['delete_time'] = time();
        Db::name('Goods')->where(['eid'=>$eid])->update($data);

        add_log('delete_all', $eid, $data);
        return to_assign(0, "清除成功");

    }

    /**
     * 生成商品编号
     * @param $param
     * @return string
     */
    protected function code($param){

        return 'XM-'.$param['eid'].'-'.time();

    }

}
